package com.qk.state.service;

import com.qk.enums.ClueEvent;
import com.qk.enums.ClueState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 线索状态机服务类
 * 只负责状态流转逻辑，不操作数据库
 * @author 28188
 */
@Slf4j
@Service
public class ClueStateMachineService {

    @Autowired
    private StateMachineFactory<ClueState, ClueEvent> factory;
    @Autowired
    private StateMachinePersister<ClueState, ClueEvent, String> persister;

    public void sendEvent(String clueId, ClueEvent event, Map<String, Object> extraHeaders) {
        StateMachine<ClueState, ClueEvent> sm = factory.getStateMachine(clueId);
        try {
            persister.restore(sm, clueId);
        } catch (Exception e) {
            throw new RuntimeException("状态机恢复异常", e);
        }

        // 打印当前状态
        log.info("发送事件前，线索 {} 当前状态: {}", clueId, sm.getState().getId());

        MessageBuilder<ClueEvent> builder = MessageBuilder
                .withPayload(event)
                .setHeader("clueId", clueId);
        if (extraHeaders != null) {
            extraHeaders.forEach(builder::setHeader);
        }
        Message<ClueEvent> msg = builder.build();

        boolean b = sm.sendEvent(msg);
        log.info("状态机执行结果: {}", b);

        // 打印当前状态
        log.info("发送事件前，线索 {} 当前状态: {}", clueId, sm.getState().getId());

        try {
            persister.persist(sm, clueId);
        } catch (Exception e) {
            throw new RuntimeException("状态机持久化异常", e);
        }
    }
}